package fr.emse.tatiana.replayable.tabulardisplay;

import java.util.Vector;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.part.EditorActionBarContributor;

import fr.emse.tatiana.TatianaConstants;

public class DisplayEditorContributor extends EditorActionBarContributor {

	SaveAsEditableAction saveaseditable;
	SaveAsExcelAction savetoexcel;
	Vector<SaveAsExportedAction> export;
	
	public DisplayEditorContributor() {
		super();
		saveaseditable = new SaveAsEditableAction("Save an editable copy...");
		savetoexcel = new SaveAsExcelAction("Excel...");
		export = new Vector<SaveAsExportedAction>();
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(TatianaConstants.TATIANA_PROJECT_NAME);

		IFolder scripts = project.getFolder(TatianaConstants.SCRIPTS_FOLDER_NAME);
		try {
			IResource[] files = scripts.members();
			for (int i=0; i<files.length; i++) {
				String name = files[i].getName();
				if (name.startsWith("export-to-")) {
					export.add(new SaveAsExportedAction(name.substring(10, name.length()-3)+"...",name));
				}
			}
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.part.EditorActionBarContributor#contributeToMenu(org.eclipse.jface.action.IMenuManager)
	 */
	@Override
	public void contributeToMenu(IMenuManager menuManager) {
		super.contributeToMenu(menuManager);
		IMenuManager fileMenu = menuManager
				.findMenuUsingPath(IWorkbenchActionConstants.M_FILE);
		
		final IMenuManager exportMenu = fileMenu.findMenuUsingPath(TatianaConstants.M_EXPORT_ACTION);
		exportMenu.add(savetoexcel);
		for (IAction action : export) {
			exportMenu.add(action);
		}
		fileMenu.insertAfter(ActionFactory.SAVE_AS.getId(), saveaseditable);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.part.EditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
	 */
	@Override
	public void setActiveEditor(IEditorPart targetEditor) {
		super.setActiveEditor(targetEditor);
		if (targetEditor instanceof ReplayableTabularViewer) {
			saveaseditable.setEditor(targetEditor);
			savetoexcel.setEditor(targetEditor);
			for (SaveAsExportedAction action : export) {
				action.setEditor(targetEditor);
			}
		} else {
			saveaseditable.setEditor(null);
			savetoexcel.setEditor(null);
			for (SaveAsExportedAction action : export) {
				action.setEditor(null);
			}
		}
	}
	
	

}
